import 'package:flutter/material.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:baseProjectFlutter/utils/other/log/log.dart';

import '../../utils/lifecycle/lifecycle.dart';

//自定义Widget  BaseWidget 方便管理StatefulWidget
abstract class BaseWidget extends StatefulWidget {
  const BaseWidget({super.key});
}

///自定义Widget
abstract class BaseWidgetState<T extends BaseWidget> extends State<T> with WidgetsBindingObserver, LifecycleOwner {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }
}

///自定义Widget
abstract class BaseMvvmWidgetState<T extends BaseWidget, VM extends BaseWidgetViewModel> extends BaseWidgetState<T> {
  //主要的ViewMode
  late VM vm;

  BaseMvvmWidgetState(this.vm);

  void initState() {
    super.initState();
    vm.lifecycleOwner = this;
    vm.initState();
  }

  @mustCallSuper
  @override
  Widget build(BuildContext context) {
    vm.context = context;
    return super.build(context);
  }
}

/// 自定义Widget Vm
abstract class BaseWidgetViewModel extends GetxController {
  BuildContext? context;
  LifecycleOwner? lifecycleOwner;
  bool _isDispose = false;
  bool _isFirst = true;

  LifecycleOwner get requireLife => lifecycleOwner!;

  BaseWidgetViewModel();

  void initState() {
    //保证只调用一次
    if (_isFirst) {
      _isFirst = false;
      onCreate();
    }
  }

  bool get isDispose => _isDispose;

  @protected
  void onCreate() {}

  void notifyListeners() {
    if (!_isDispose) {
      try {
        super.update();
      } catch (e, t) {
        LogUtils.e("BaseWidgetViewModel notifyListeners error:$e,t:$t");
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    _isDispose = true;
    lifecycleOwner = null;
  }
}
